package gae.testjig.dao;

import gae.testjig.dto.Contact;

import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class DaoContact {
	
	static public Contact create(PersistenceManager pm, Key orgKey, String name, String phoneNumber) {
		return create(pm, orgKey, name, phoneNumber, null);
	}

	static public Contact create(PersistenceManager pm, Key orgKey, String name, String phoneNumber, Key contactGroupKey) {
		// be sure the key is in the same entity group as the organization.
		String contactUnique = name + phoneNumber;
		Key contactKey = KeyFactory.createKey(orgKey, Contact.class.getSimpleName(), contactUnique);
		
		Contact contact = new Contact();
		contact.setContactKey(contactKey);
		contact.setOrganizationKey(orgKey);
		contact.setName(name);
		contact.setPhoneNumber(phoneNumber);
		LinkedList<Key> list = new LinkedList<Key>();
		if ( contactGroupKey != null ) {
			list.add(contactGroupKey);
		}
		contact.setContactGroups(list); // start with empty list.
		pm.makePersistent(contact);
		return contact;
	}
	
	static public List<Contact> findByContactGroup(PersistenceManager pm, Key contactGroupKey) throws DaoException {
		Query query = pm.newQuery(Contact.class);
		query.setFilter("contactGroups == contactGroupsParam");
		query.setOrdering("name asc");
		query.declareImports("import com.google.appengine.api.datastore.Key");
		query.declareParameters("Key contactGroupsParam");
		@SuppressWarnings("unchecked")
		List<Contact> results = (List<Contact>) query.execute(contactGroupKey);
		return results;
	}

	public static List<Contact> findByOrganization(PersistenceManager pm, Key orgKey) {
		Query query = pm.newQuery(Contact.class);
		query.setFilter("organizationKey == organizationKeyParam");
		query.setOrdering("name asc");
		query.declareImports("import com.google.appengine.api.datastore.Key");
		query.declareParameters("Key organizationKeyParam");
		@SuppressWarnings("unchecked")
		List<Contact> results = (List<Contact>) query.execute(orgKey);
		return results;
	}

	public static Contact findByContactKey(PersistenceManager pm, Key contactKey) throws DaoException {
		Contact c = (Contact) pm.getObjectById(Contact.class, contactKey);
		if ( null == c ) {
			throw new DaoNotFoundException("no such contact found.");
		}
		return c;
	}
	
}
